package com.blackman.skcrawler.core.http.request;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.Future;

/**
 * 发送http请求
 *
 * @author staywood_zjb
 * @date 2018/4/03 20:50
 *
 */
public class HttpRequest {

    private static Header[] headers = new Header[1];

    private static RequestConfig.Builder defaultBuilder = RequestConfig.custom().setConnectTimeout(15000).setSocketTimeout(15000);

    private static CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();

    static{
        httpclient.start();
        headers[0] = new BasicHeader("User-Agent", "Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Mobile Safari/537.36");
    }

    /**
     * 发送http get响应
     * @param url
     * @return
     */
    public HttpResponse sendHttpGetRsp(String url){
        HttpGet httpGet = new HttpGet(url);
        Future<HttpResponse> future = httpclient.execute(httpGet, null);
        try {
            httpGet.setConfig(defaultBuilder.build());
            httpGet.setHeaders(headers);
            HttpResponse httpResponse = future.get();
            return httpResponse;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
//            try {
//                httpclient.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
        }
        return null;
    }

    /**
     * http get 请求
     * @param url 请求地址
     */
    public String sendHttpGet(String url){
        // 执行请求
        HttpResponse response = sendHttpGetRsp(url);
        String stringBuffer = getRspContent(response);
        return stringBuffer;
    }

    /**
     * 获取响应内容
     * @param response
     * @return
     */
    public String getRspContent(HttpResponse response){
        if(response == null){
            return null;
        }
        try {
            HttpEntity entity = response.getEntity();
            Charset charset = ContentType.getOrDefault(entity).getCharset();
            String charsetstr  = "gb2312";
            if(charset != null){
                charsetstr = charset.toString();
            }
            String respContent = EntityUtils.toString(entity, charsetstr).trim();
            return respContent;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
